package com.sample.controller;

import com.sample.entity.User;
import com.sample.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author Keyon
 * @Date 2019/11/29 13:49
 * @Desc 用户-控制层
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public ModelAndView findAll(ModelAndView mv) {
        List<User> userList = userService.findAll();
        userList.forEach(User::toString);
        mv.addObject("list", userList); //添加传递的数据
        mv.setViewName("list"); //找View层中的list.jsp
        return mv;
    }

    @PostMapping("/save")
    public void saveUser(HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestParam("userName") String userName,
                            @RequestParam("email") String email) throws IOException {
        System.out.println(userName + "  " + email);
        userService.saveUser(userName, email);
        response.sendRedirect(request.getContextPath() + "/user/findAll");
    }

    @GetMapping("/{id}")
    public ModelAndView findUserById(@PathVariable("id") Integer id,
                                     ModelAndView mv) {
        User user = userService.findUserById(id);
        System.out.println(user);
        mv.addObject("user", user);
        mv.setViewName("userInfo");
        return mv;
    }

}
